//实现数组的flat方法
Array.prototype._flat = function (depth) {
  if (!Array.isArray(this) || depth <= 0) return this;

  return this.reduce((res, item) => {
    return res.concat(
      Array.isArray(item) ? Array.prototype._flat.call(item, depth - 1) : item
    );
  }, []);
};

const arr = [1, [2, 3, [4]], 5, 6];
// console.log(arr._flat(2));

//实现数组的push方法
Array.prototype._push = function (...args) {
  console.log(args);
  for (let i = 0; i < args.length; i++) {
    this[this.length] = args[i];
  }
  return this.length;
};

// console.log(arr._push(5, 6));

//实现数组的filter方法
Array.prototype._filter = function (fn) {
  if (typeof fn !== "function") throw new Error("参数必须为函数");
  const res = [];
  for (let i = 0; i < this.length; i++) {
    fn(this[i]) && res.push(this[i]);
  }
  return res;
};

// console.log(arr._filter((item) => item === 5));

//实现数组的map方法
Array.prototype._map = function (fn) {
  if (typeof fn !== "function") throw new Error("参数必须为函数");
  const res = [];
  for (let i = 0; i < this.length; i++) {
    res.push(fn(this[i]));
  }
  return res;
};

// console.log(arr._map((item) => typeof item));
// console.log(arr.map((item) => undefined));
